import React, { useState } from "react";
// PDF 解析编辑工具库
// import { PDFDocument } from "pdf-lib";
import { readFileAsync, renderPdf, extractPdfPage } from "./tools";
import PdfHightlighter from "./PdfHightlighter";

export default function PdfLib() {
  const [pdfFileData, setPdfFileData] = useState();

  // 当用户选择一个文件时，获取上传的PDF文件解析
  const onFileSelected = async (e) => {
    const fileList = e.target.files;
    if (fileList?.length > 0) {
      const pdfArrayBuffer = await readFileAsync(fileList[0]);
      const newPdfDoc = await extractPdfPage(pdfArrayBuffer);
      setPdfFileData(renderPdf(newPdfDoc));
    }
  };

  return (
    <div>
      PdfLib
      <input type="file" accept=".pdf" onChange={onFileSelected} />
      {/* 显示区域 */}
      <iframe
        style={{ display: "block", width: "90vw", height: "70vh" }}
        title="PdfFrame"
        src={pdfFileData}
        frameBorder="0"
        type="application/pdf"
      ></iframe>
      {pdfFileData && <PdfHightlighter pdfUrl={pdfFileData}></PdfHightlighter>}
    </div>
  );
}
